package com_.dxy_test_.diy_tomcat_;

import com_.dxy_test_.diy_tomcat_.servlet_.HelloServlet;
import com_.dxy_test_.diy_tomcat_.servlet_.HelloServlet2;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description 手写tomcat
 * @Author dangxianyue
 * @Date 2022/9/26 11:39
 */
public class MyTomcat {

    private static final Map<String, MyServlet> MAP;
    static {
        MAP = new HashMap<>();
        MAP.put("/hello", new HelloServlet());
        MAP.put("/hello2", new HelloServlet2());
    }

    private int port;

    public MyTomcat(int port) {
        this.port = port;
    }


    public static void main(String[] args) {
        new MyTomcat(8000).start();
    }

    public void start() {
        ServerSocket serverSocket = null;
        try {
            System.out.println("服务启动中,端口：" + port);
            serverSocket = new ServerSocket(port);
            while (true) {
                Socket socket = serverSocket.accept();
                MyRequest request = new MyRequest(socket.getInputStream());
                MyResponse response = new MyResponse(socket.getOutputStream());
                dispatch(request, response);
                //流对象in封装在socket中，自动关闭流对象；
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("ssss");
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 模拟请求分发
     * @param myRequest
     * @param myResponse
     */
    private void dispatch(MyRequest myRequest, MyResponse myResponse) throws IOException {
        MyServlet myServlet = MAP.get(myRequest.getUrl());
        if (myServlet == null) {
            myResponse.write("Servlet不存在！");
            return;
        }
        myServlet.service(myRequest,myResponse);
    }

}
